const colors = require('colors')

// ============================================================

const arr = [2, 5, 7, 4, 3, 4, 3, 7, 8, 7, 5, 4, 4, 3]
const arr_02 = [1, 2, 3, 4, 5, 6, 7]

class Difference {
  /**
   * 初始化差分数组
   */
  constructor(arr) {
    // 获取差分数组
    this._diffArray = this.getDiffArray(arr)
  }

  /**
   * 获取差分数组
   * @param {array} arr 原数组
   * @returns {array} 差分数组
   */
  getDiffArray = function (arr) {
    let arr_diff = []
    arr_diff.push(arr[0])
    arr.reduce((diff, current) => {
      diff = current - diff
      arr_diff.push(diff)
      return current
    })
    //   console.log(arr_diff)
    return arr_diff
  }

  /**
   * 整体对数组某一部分增减
   * @param {number} start 起始点
   * @param {number} end 结束点
   * @param {number} value 整体增长值(可为负数)
   */
  arrayIncrement = function (start, end, value) {
    let condition_legal = start >= 0 && end >= 0
    let condition_no_overflow = this._diffArray.length > start && this._diffArray.length > end
    if (condition_legal && condition_no_overflow) {
      this._diffArray[start] += value
      this._diffArray[end + 1] -= value
      return this.getFinalArray()
    }
    return 'Error: param illegal !!!'.red
  }

  /**
   * 获取数组原始值
   * @returns {array}
   */
  getFinalArray = function () {
    let res = []
    res.push(this._diffArray[0])
    this._diffArray.reduce((sum, current) => {
      sum += current
      res.push(sum)
      return sum
    })
    return res
  }
}

// 测试区间 --------------------------------

// 第一个测试
// console.log(new Difference(arr)._diffArray)

// 第二个测试
// let diff_array_01 = new Difference(arr_02)
// console.log(diff_array_01._diffArray)
// console.log(diff_array_01.getFinalArray())

// 第三个测试
// let diff_array_01 = new Difference(arr_02)
// console.log(diff_array_01.arrayIncrement(2, 4, 5))
// console.log(diff_array_01.arrayIncrement(2, 12, 5))

// 第四个测试
console.log(new Array(10).fill(0, 20, 40))
